<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 11:18
 */

namespace Modules\SmallApi\Service;

use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\RepairstoreGoodsRepository;
use HiCommon\Repository\CouponsRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\UsersLevelRepository;
use HiCommon\Repository\EquitiesRepository;
use HiCommon\Repository\ActivityRepository;
use HiCommon\Repository\LogRepository;

class CouponService extends BaseService
{

	
	/**
	 *	我的优惠券
	 *	hinq 2019 09 02
	 *	应用场景【个人中心 优惠券】
	 **/
	public function get_all( array $arr_search ){

		if( empty( small_api_user_id() ) ){
			return ['state'=> 1,'msg'=>'请登录','data'=>[],'error'=>''];	
		}

		$arr_where['where'] = ['user_id'=> small_api_user_id() ];
		$arr_where['with'] = ['getCouponInfoAll'];
		$arr_where['order'] = ['key'=>'status','value'=>'asc'];
		$arr_where['field'] = ['id','user_id','coupon_id','pid','over_at','ticket_num','msg','integral','status','created_at'];
		$res = CouponGrantDetailRepository::get_list((array) $arr_search , (array) $arr_where )->toarray();
		$coupon_types = ['1'=>'洗车券','2'=>'满减券','3'=>'折扣券'];
		foreach ($res['data'] as $key => &$value) {
			$value['get_coupon_info_all']['discount_num'] = floatval($value['get_coupon_info_all']['discount_num']); 
			$value['get_coupon_info_all']['price'] = floatval($value['get_coupon_info_all']['price']); //保留有效的小数位
			$value['over_at'] = date( 'Y-m-j' , $value['over_at'] );
				$value['pid_msg'] = $coupon_types[$value['pid']];
			if( $value['pid'] == 1 ){
				$value['remarks'] = $coupon_types[$value['pid']];
			}else if( $value['pid'] == 2 ){
				$value['remarks'] = '满'.intval($value['get_coupon_info_all']['price_all']).'元减'.$value['get_coupon_info_all']['price'].'元';
			}else if( $value['pid'] == 3 ){
				$value['remarks'] = '满'.intval( $value['get_coupon_info_all']['price_all'] ).'元打'.$value['get_coupon_info_all']['discount_num'].'折';
			}
			$value['created_at'] = date( 'Y-m-j' ,strtotime( $value['created_at'] ) );
		}
		$arr_list = [
          	'page'=>[
	            'current_page'=>$res['current_page'],
	            'last_page'=>$res['last_page'],
	            'per_page'=>$res['per_page'],
	            'total'=>$res['total'],
          	],
          	'data'=>$res['data'],
        ];
		return ['state'=> 0,'msg'=>'ok','data'=>$arr_list,'error'=>''];	
	}


	/**
	 *	获取优惠券详情数据
	 *	hinq 2019 09 10
	 *
	 **/
	public function get_one( int $nId ){
		try{
			if( empty( $nId ) ){
                return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
            }
            $arr_where['with'] = ['getCouponInfo'];
            $res = CouponGrantDetailRepository::get_one( (int) $nId , (array) $arr_where );
            $result = hi_check_res($res,'get_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'获取失败','data'=>[],'error'=>''];
	        }

	        $data['ticket_num'] = $res['ticket_num'];
	        $data['content'] = $res['getCouponInfo']['content'];
	        $data['coupon_id'] = $res['coupon_id'];
	        $data['pid'] = $res['pid'];

			return ['state'=> 0,'msg'=>'ok','data'=>$data,'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}



	/**
	 *	使用优惠券
	 *	hinq 2019 09 02
	 *	应用场景【个人中心 扫描二维码使用优惠券】
	 **/
	public function edit_one( array $arr_search ){

		try{
			if( empty( $arr_search ) ){
				return ['state'=> 1,'msg'=>'优惠券扫描失败，请重新扫描','data'=>[],'error'=>''];
			}

			$arr_option['field'] = ['id','status','over_at'];
			$arr_info = CouponGrantDetailRepository::get_one_where( (array) $arr_search , (array) $arr_option );
			
			if( empty( $arr_info->first() ) ){
	            return ['state'=> 1,'msg'=>'优惠券有误，请稍后重试','data'=>[],'error'=>''];
			}
			if( $arr_info['over_at'] <= time() ){
	            return ['state'=> 1,'msg'=>'该优惠券已过期','data'=>[],'error'=>''];
			}

			if( $arr_info['status'] == 2){
	            return ['state'=> 1,'msg'=>'该优惠券已经使用过','data'=>[],'error'=>''];
			}
			if( $arr_info['status'] == 3){
	            return ['state'=> 1,'msg'=>'该优惠券已过期','data'=>[],'error'=>''];
			}
			
			$temp['id'] = $arr_info['id'];
			$temp['status'] = 2;

			$res = CouponGrantDetailRepository::edit_one( (array) $temp );
			$result = hi_check_res($res,'edit_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'优惠券使用失败','data'=>[],'error'=>''];
	        }
	        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}

	

	/**
	 *	商城下订单时获取有效的优惠券
	 *	hinq 2019 09 09 
	 *	array['g_id']  商品id
	 *	array['type']  类型
	 *  如果是门店优惠券 就只能在发布的门店商品中使用  平台发布的优惠券 所有门店商品都可用
	 **/
	public function get_my_coupon_to_goods( array $arrInput ){
		$arrInput['type'] = empty( $arrInput['type'] ) ? 2 : $arrInput['type'];

		if( empty( $arrInput['goods_id'] ) || empty( $arrInput['type'] ) ){
	        return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
		}
		
		//获取订单商品的信息
		if( $arrInput['type'] == 1 ){   //积分商品不可以使用优惠券
	        return ['state'=> 1,'msg'=>'积分商品不能使用优惠券','data'=>[],'error'=>''];
	    }else if( $arrInput['type'] == 2 ){ // 维修店的服务订单
	    	$arr_where['field'] = ['id','repairstore_id','price'];
			$arr_where['with'] = ['shop'];
			$arr_where['where'] = [ 'id' => $arrInput['goods_id'] ];
			$goods_info = RepairstoreGoodsRepository::get_all( (array) $arr_where )->toArray();
	    }

	    //获取当前用户所有未使用的优惠券【购买商品时只能使用满减券和折扣券】
		$where['where'] = [ 'user_id' => small_api_user_id() , 'status' => 1];
		$where['with'] = ['getCouponInfo'=>function($query)use($goods_info){
           $query->whereIn('repairstore_id',[$goods_info[0]['repairstore_id'], 0]);
		}]; //这里关联了优惠券主表，只能使用当前店铺和平台发布的优惠券 ， A维修店不可以使用B维修店发布的优惠券
		$arr_info = CouponGrantDetailRepository::get_all_to_goods( (array) $where );
		$arr_list = [];
		$coupon_types = ['1'=>'洗车券','2'=>'满减券','3'=>'折扣券'];
		foreach ($arr_info->toArray() as $key => &$value) {
			//          优惠券的最低消费价格                      <           商品的价格
			if( intval( $value['get_coupon_info']['price_all'] )  <= intval( $goods_info[0]['price'] ) ){  //可以使用优惠券
				$temp['price'] = $value['get_coupon_info']['price'];
				$temp['discount_num'] = $value['get_coupon_info']['discount_num'];
				$temp['price_all'] = $value['get_coupon_info']['price_all'];
				$temp['content'] = $value['get_coupon_info']['content'];
				$temp['start_time'] = date('Y-m-d' , strtotime($value['created_at']));
				$temp['over_at'] = date('Y-m-d' , $value['over_at']);
				$temp['pid_msg'] = $coupon_types[$value['pid']];
				$temp['pid'] = $value['pid'];
				$temp['coupon_id'] = $value['coupon_id'];
				$temp['id'] = $value['id'];
				$arr_list[] = $temp;
			}
		}
	    return ['state'=> 0,'msg'=>'ok','data'=>$arr_list,'error'=>''];
	}



	/**
	 *	手动给用户发放优惠券
	 *	hinq 2019 09 24
	 *
	 **/
	public function create_coupon_to_user( array $arrInput ){

		if( empty( $arrInput['user_id'] ) ){
			return ['state'=> 1,'msg'=>'用户id不能为空','data'=>[],'error'=>''];
		}

		if( empty( $arrInput['coupon_id'] ) ){
			return ['state'=> 1,'msg'=>'优惠券id不能为空','data'=>[],'error'=>''];
		}
		//获取优惠券的信息
		$coupon_info = CouponsRepository::get_one( (int) $arrInput['coupon_id'] )->toArray();
		if( empty( $coupon_info ) ){
			return ['state'=> 1,'msg'=>'获取优惠券信息错误','data'=>[],'error'=>''];
		}
		$data['user_id'] = $arrInput['user_id'];
		$data['coupon_id'] = $arrInput['coupon_id'];
		$data['pid'] = $coupon_info['pid'];
		$data['over_at'] = intval( $coupon_info['validity_at'] * 3600 * 24 + time() );
		$data['ticket_num'] = set_coupons_ticket_num( $coupon_info['pid'] );
		$data['msg'] = '测试手动发放';
		$data['integral'] = 100;
		$data['status'] = 1;
		$data['type'] = 1;
		$res = CouponGrantDetailRepository::add_one( (array) $data );
		$result = hi_check_res($res,'add_one');
        if ($result['state'] != 0 ) {
            return ['state'=> 1,'msg'=>'优惠券发放失败','data'=>[],'error'=>''];
        }
        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
	}


	/**
	 *	会员升级发放会员等级礼包
	 *	hinq 2019 09 26
	 *	先将用户获得的积分更新到数据库中在调用此接口
	 **/
	public function send_upgrade_material_benefits( int $nId ){
        return '挪至公共PublicService中';
		try{
			if( empty( $nId ) ){
        		return ['state'=> 1,'msg'=>'用户id不能为空','data'=>[],'error'=>''];
			}
			//获取用户的积分信息
			$user_info = UsersRepository::get_one( (int) $nId , (array) ['field'=>['id','integral','integral_all']]);

			//获取会员等级列表
			$user_level = UsersLevelRepository::get_all( (array) ['order'=>['key'=>'min_integral' ,'value'=>'asc'] ,'field'=>['id','name','min_integral','max_integral','equities']]);

			$user_new_level = [];  //会员所属的会员等级
			//检测当前用户会员等级
			foreach ($user_level->toArray() as $key => $value) {
				//      会员当前的总积分         >=      会员等级的最低积分      会员当前的总积分          <=     会员等级的最大积分
				if( $user_info['integral_all'] >= $value['min_integral'] && $user_info['integral_all'] <= $value['max_integral']){
					$user_new_level = $value;  //获取当前会员所属的会员等级
				}
			}
			
			//获取当前所属等级的所有权益
			$equities_ids = explode(',', $user_new_level['equities'] );  //当前等级的所有权益
			$level_equities = EquitiesRepository::get_all_by_whereIn( (array) $equities_ids , (array) ['with'=>['get_equities']] );

			$coupon_list = [];  //权益的优惠券礼包集合
			foreach ($level_equities->toArray() as $key => $value) {
				if( count( $value['get_equities'] ) > 0 ){
					//获取需要发放的优惠券数据
					foreach ($value['get_equities'] as $k => $val) {
						//升级时一次性优惠券 和每月固定的优惠券 在会员升级时都发放一次
						$coupon_list['coupon'][] = $val['coupon_id'];
						$coupon_list['num'][] = $val['num'];
						$coupon_list['equities'][] = $value['id'];
					}
				}
			}

			if( count( $coupon_list ) <= 0 ){
        		return ['state'=> 0,'msg'=>'暂无礼包发放','data'=>[],'error'=>''];
			}

			//获取权益礼包中包含的所有优惠券信息
			$coupon = CouponsRepository::get_all_by_whereIn( (array) array_unique($coupon_list['coupon'] ) ,(array)['field'=>['id','pid','validity_at']]);
			$coupon_pids = [];
			foreach ($coupon as $key => $value) {
				$coupon_pids[$value['id']]['pid'] = $value['pid'];
				$coupon_pids[$value['id']]['validity_at'] = $value['validity_at'];
			}
			// dd( $coupon_list );
			//检测当前用户是否已经发放过升级礼包
			foreach ($coupon_list['coupon'] as $key => $value) {

				$arr_map['user_id'] = $nId;
				$arr_map['coupon_id'] = $value;
				$arr_map['type'] = 1;
				$arr_map['user_level'] = $user_new_level['id'];
				$arr_map['equities'] = $coupon_list['equities'][$key];
				//升级礼包是一起发放的 如果有发放过升级礼包所有的礼包都不发放 否则发放
				if( CouponGrantDetailRepository::get_count_by_where( (array) $arr_map ) >= 1){
        			return ['state'=> 0,'msg'=>'升级礼包已发放，请勿重复发放','data'=>[],'error'=>''];
				}
				$temp['user_id'] = $nId;
				$temp['coupon_id'] = $value;
				$temp['msg'] = '会员升级发放会员等级礼包';
				$temp['integral'] = $user_info['integral_all'];
				$temp['status'] = 1;
				$temp['type'] = 1;
				$temp['user_level'] = $user_new_level['id'];
				$temp['equities'] = $coupon_list['equities'][$key];

				for ($i=1; $i <= $coupon_list['num'][$key] ; $i++) { 
					$temp['pid'] = $coupon_pids[$value]['pid'];
					$temp['over_at'] = $coupon_pids[$value]['validity_at'] * 3600 * 24 + time();
					$temp['ticket_num'] = set_coupons_ticket_num( $coupon_pids[$value]['pid'] );
					$res = CouponGrantDetailRepository::add_one( $temp );
					$result = hi_check_res($res,'edit_one');
			        if ($result['state'] != 0) {
			            return ['state'=> 1,'msg'=>'升级礼包发放失败','data'=>[],'error'=>''];
			        }
				}
		    }
		    return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }

	}




//=======================定时任务==========================================================

	/**
	 *	定时任务调用
	 *  修改已过期的并且未使用的优惠券的状态
	 *	hinq 2019 09 23
	 *
	 **/
	public function change_coupon_status(){

		//获取未使用并且即将要到期的优惠券(查找条件：过期时间小于当前时间戳 && 优惠券状态为未使用状态 )
		$arr_list = CouponGrantDetailRepository::get_timed_task_list()->toArray();
		$ids = [];  //需要修改的数据集合
		$str = '';
		foreach ($arr_list as $key => $value) {
			$ids[] = $value['id'];
			$str.= $value['id'] . ',';
		}
		//修改优惠券的状态 status = 3 已使用状态
		$res = CouponGrantDetailRepository::edit_timed_task_list( (array) $ids );
		$result = hi_check_res($res,'edit_one');
        if ($result['state'] != 0) {
            return ['state'=> 1,'msg'=>'优惠券状态修改失败','data'=>[],'error'=>''];
        }
        return ['state'=> 0,'msg'=>'ok [共'.count( $ids ).'条数据过期，主键集合为：'. trim( $str ).']','data'=>[],'error'=>''];
	}


	/**
	 *	定时任务调用
	 *	给会用用户发放设定的福利礼包
	 *	hinq 2019 09 26
	 *	思路   获取所有会员等级   在查出所有会员等级设置的权益  在查出每一项权益是否有礼包需要发放（每月发放的礼品，一次性发放的礼品会员升级的时候发放）
	 		   获取所有满足会员等级的用户列表 ， 然后循环发放礼品	 
	 **/
	public function send_material_benefits(){
		
		$arr_map['status'] = 1;
		$data = UsersRepository::get_all_by_where_between( (array) $arr_map ,(array) ['field'=>['id','integral','integral_all']]);



		//获取会员等级列表
		$user_level = UsersLevelRepository::get_all( (array) ['order'=>['key'=>'min_integral' ,'value'=>'asc'] ,'field'=>['id','name','min_integral','max_integral','equities']]);
		$temp = [];  //会员等级下需要发放的所有会员列表集合
		foreach ($user_level->toArray() as $key => $value) {
			foreach ($data->toArray() as $k => $val) {
				if( $val['integral_all'] >= $value['min_integral'] && $val['integral_all'] <= $value['max_integral'] ){
					$temp[$value['id']]['user'][] = $val;
					$value['arr_equities'] = explode(',', $value['equities']);
					$temp[$value['id']]['usersLeve'] = $value;
					unset( $val );
				}
			}
		}
        if( count( $temp ) <= 0 ){
            return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
        }
		//获取所有权益以及权益礼包
		$level_equities = EquitiesRepository::get_all( (array) ['with'=>['get_equities']] );
		$coupon_ids = [];
		$equities_list = [];
		foreach ($level_equities->toArray() as $key => $value) {
			$equities_list[$value['id']] = [];
			if(  count( $value['get_equities'] ) > 0 ){
				foreach ($value['get_equities'] as $k => $val ) {
					if( $val['type'] == 2 ){  // type ==2  每月发放
						$coupon_ids[] = $val['coupon_id'];
						$equities_list[$value['id']] = $value['get_equities'];
					}
				}
			}
		}
		//获取权益礼包中包含的所有优惠券信息
		$coupon = CouponsRepository::get_all_by_whereIn( (array) array_unique( $coupon_ids ) ,(array)['field'=>['id','pid','validity_at']]);
		$coupon_pids = [];
		foreach ($coupon as $key => $value) {
			$coupon_pids[$value['id']]['pid'] = $value['pid'];
			$coupon_pids[$value['id']]['validity_at'] = $value['validity_at'];
		}

		foreach ($temp as $key => $value) {
			foreach ($value['user'] as $k => $val) {
					$temps['user_id'] = $val['id'];
					$temps['msg'] = '每月发放会员等级礼包';
					$temps['integral'] = $val['integral_all'];
					$temps['status'] = 1;
					$temps['type'] = 1;
					$temps['user_level'] = 3;
					$temps['equities'] = $value['usersLeve']['id'];
				foreach ($equities_list as $j => $vo) {
					if(  !empty( $vo ) && in_array( $j, $value['usersLeve']['arr_equities'])){
						foreach ( $vo as $k => $item) {
							for( $i = 1 ; $i <= $item['num'] ; $i++){
								$temps['coupon_id'] = $item['coupon_id'];
								$temps['pid'] = $coupon_pids[$item['coupon_id']]['pid'];
								$temps['over_at'] = $coupon_pids[$item['coupon_id']]['validity_at'] * 3600 * 24 + time();
								$temps['ticket_num'] = set_coupons_ticket_num( $coupon_pids[$item['coupon_id']]['pid'] );
								$res = CouponGrantDetailRepository::add_one( $temps );
								$result = hi_check_res($res,'edit_one');
						        if ($result['state'] != 0) {
						            return ['state'=> 1,'msg'=>'升级礼包发放失败','data'=>[],'error'=>''];
						        }
							}
						}
					}
				}
			}
		}
		return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
	}

    /**
     *	定时任务调用    // 刚接口挪到app/console/commands中      app/console/kernel.php中调用
     *  定期检测活动是否到期
     *	hinq 2019 09 23
     *
     **/
    public function activity_auto_cancel(){
        //获取所有的活动列表
        $arr_option['where'] = ['status'=>1];
        $arr_option['field'] = ['id','start_time','over_time','repairstore_id'];
        $arr_option['with'] = ['activity_goods_extend'];
        $arr_list = ActivityRepository::get_all( (array) $arr_option )->toArray();
        $str = '';
        $num = 0;
        foreach ( $arr_list as $key => $vo ){
            // 活动的结束时间小于当前时间    获取已过期
            if( $vo['over_time'] < time() ){
                $str .= $vo['id'] .',';
                $num++;
                //将活动状态设置为已过期
                ActivityRepository::change_one_state( (int) $vo['id'] , (int) 4 );

                //将活动设置的商品设置为普通商品
                $ids = '';
                foreach ( $vo['activity_goods_extend'] as $k => $v){
                    $ids .= ',' . $v['goods'];
                }
                $ids = explode(',',trim( $ids , ',') );
                if( $ids[0] ){
                    GoodsRepository::edit_whereIn( (array) $ids , (array) ['type'=>1]);
                }
            }
        }
        //添加日志
        $log_data['time'] = date("Y-m-d H:i:s");
        $log_data['num'] = $num;
        $log_data['activity_ids'] = trim( $str , ',');
        $temp = 'ok, 成功修改'.$num.'条活动数据，【'.  $log_data['activity_ids'] . '】';

        LogRepository::record_change_activity( (array) $log_data );
        return hello_success($temp);
    }



//      banner表
//      coupons表
//      equities表
//      shop_server_type表
//      user_invite_set表
//      users_level表






}